package com.LeeCode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的堂兄弟节点 II
 */

public class Code2641 {
    public static void main(String[] args) {

    }

    public TreeNode replaceValueInTree(TreeNode root) {
        root.val = 0;
        Deque<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            Deque<TreeNode> tmp = q;
            q = new LinkedList<>();

            // 计算下一层的节点值之和
            int nextLevelSum = 0;
            for (TreeNode node : tmp) {
                if (node.left != null) {
                    q.offer(node.left);
                    nextLevelSum += node.left.val;
                }
                if (node.right != null) {
                    q.offer(node.right);
                    nextLevelSum += node.right.val;
                }
            }

            // 再次遍历，更新下一层的节点值
            while (!tmp.isEmpty()) {
                TreeNode node = tmp.poll();
                int childrenSum = (node.left != null ? node.left.val : 0) +
                        (node.right != null ? node.right.val : 0);
                if (node.left != null) node.left.val = nextLevelSum - childrenSum;
                if (node.right != null) node.right.val = nextLevelSum - childrenSum;
            }
        }
        return root;
    }
}
